import {
    Button,
    Form,
    Input,
    InputNumber,
    Select,
    TimePicker,
    Cascader,
    Upload,
    Table,
    Space,
    Popconfirm,
    Modal,
    message,
    Checkbox,
    Row,
    Col,
} from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import type { RcFile } from 'antd/es/upload/interface';
import type { ColumnsType } from 'antd/es/table';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import React, { useEffect, useState } from 'react';
import { getCategoryList, addRest } from "../../api/request";

const { Option } = Select;
const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
};
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};
const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('您只能上传 JPG/PNG 格式!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

interface Option {
    value: string;
    label: string;
    children?: Option[];
}
interface Category {
    name: string
    sub_categories?: Category[]
}
interface DataType {
    icon_name: string
    name: string
    description: string
}

const App = () => {

    const [mainForm] = Form.useForm();
    const [actForm] = Form.useForm();

    // 店铺分类
    const [category, setCategory] = useState([])
    // 格式化时间选择器
    const format = 'HH:mm'
    // 店铺特点
    const character = {
        is_premium: true,
        delivery_mode: true,
        new: true,
        piao: true,
        zhun: true,
        bao: true
    }
    const [shopCharacter, setShopCharacter] = useState(character)
    // 图片加载
    const loadings = {
        '上传店铺头像': false,
        '上传营业执照': false,
        '上传餐饮服务许可证': false
    }
    const [loading, setLoading] = useState<any>(loadings);
    // 店铺头像地址
    const [imageAvatar, setImageAvatar] = useState<string>();
    // 营业执照地址
    const [imageLicense, setImageLicense] = useState<string>();
    // 餐饮服务许可证地址
    const [imagePermit, setImagePermit] = useState<string>();
    // 对话框状态
    const [isModalOpen, setIsModalOpen] = useState(false)
    // 表格数据
    const tableData = [
        {
            icon_name: '减',
            name: '满减优惠',
            description: '满30减5，满60减8',
        },
    ]
    const [ativitiesData, setAtivitiesData] = useState<DataType[]>(tableData)

    useEffect(() => {
        getCategoryList().then(res => setCategory(res.data))
    }, [])

    // 手机号地区前缀
    const prefixSelector = (
        <Form.Item noStyle>
            <Select style={{ width: 70 }} defaultValue={'+86'}>
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
            </Select>
        </Form.Item>
    )

    // 复选框
    const onChange = (checkedValues: CheckboxValueType[]) => {
        // console.log('checked = ', checkedValues);
        let str = checkedValues.join("&")
        const obj: any = {}
        Object.keys(shopCharacter).forEach(item => {
            if (!str.includes(item)) {
                obj[item as string] = false
            }
        })
        // console.log(obj);
        setShopCharacter({
            ...shopCharacter,
            ...obj
        })
        // console.log(shopCharacter);
    };

    // 获取店铺分类
    const getOption = (data: Category[]) => {
        let optionArr: Option[] = []
        data.map((item: any) => {
            let optionItem: Option = {
                value: '',
                label: '',
            }
            if (item.sub_categories) {
                optionItem = {
                    value: item.name,
                    label: item.name,
                    children: getOption(item.sub_categories)
                }
            } else {
                optionItem = {
                    value: item.name,
                    label: item.name,
                }
            }
            optionArr.push(optionItem)
        })
        // console.log(optionArr);
        return optionArr
    }

    // 表格
    const columns: ColumnsType<DataType> = [
        {
            title: '活动标题',
            dataIndex: 'icon_name',
        },
        {
            title: '活动名称',
            dataIndex: 'name',
        },
        {
            title: '活动详情',
            dataIndex: 'description',
        },
        {
            title: '操作',
            dataIndex: 'edit',
            render: (text, record, index) => <Space>
                <Popconfirm
                    title="确定删除吗?"
                    onConfirm={() => deleteAtivities(index)}
                    onCancel={() => { }}
                    okText="确定"
                    cancelText="再想想"
                >
                    <Button danger >删除</Button>
                </Popconfirm>
            </Space>
        },
    ];

    // 上传图片
    const handleChange = (info: any, label: any) => {
        console.log(info);

        if (info.file.status === 'uploading') {
            switch (label) {
                case '上传店铺头像':
                    setLoading({
                        ...loadings,
                        '上传店铺头像': true
                    });
                    break;
                case '上传营业执照':
                    setLoading({
                        ...loadings,
                        '上传营业执照': true
                    });
                    break;
                case '上传餐饮服务许可证':
                    setLoading({
                        ...loadings,
                        '上传餐饮服务许可证': true
                    });
                    break;
                default:
                    break;
            }
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            setLoading(loadings)
            getBase64(info.file.originFileObj as RcFile, url => {
                switch (label) {
                    case '上传店铺头像':
                        setImageAvatar(info.file.response.image_path);
                        break;
                    case '上传营业执照':
                        setImageLicense(info.file.response.image_path)
                        break;
                    case '上传餐饮服务许可证':
                        setImagePermit(info.file.response.image_path)
                        break;
                    default:
                        break;
                }
            });
        }
    };

    // 选中优惠活动
    const onSelect = (value: any) => setIsModalOpen(true)

    // 取消对话框
    const onCancel = (value: any) => {
        setIsModalOpen(false)
        actForm.setFieldsValue({ description: '' })
    }

    // 获取活动标题
    const getIconName = (actName: string) => {
        switch (actName) {
            case '满减优惠':
                return '减'
                break;
            case '优惠大酬宾':
                return '特'
                break;
            case '新用户立减':
                return '新'
                break;
            case '进店领券':
                return '领'
                break;

            default:
                return '减'
                break;
        }
    }
    // 确认对话框
    const onModalFinish = (value: any) => {
        // console.log(value)
        const actName = mainForm.getFieldValue('ativities')
        tableData.push({
            icon_name: getIconName(actName),
            name: actName,
            description: value.description,
        })
        setAtivitiesData(tableData)
        setIsModalOpen(false)
        actForm.setFieldsValue({ description: '' })
    }

    // 删除活动
    const deleteAtivities = (index: any) => {
        tableData.splice(index, 1)
        setAtivitiesData(tableData)
    }

    // 提交表单 
    const onFinish = (values: any) => {
        console.log('Received values of form: ', values);
        const data = {
            ...values,
            ...shopCharacter,
            latitude: '',
            longitude: '',
            category: values.category.join("/"),
            startTime: values.startTime && values.startTime._d,
            endTime: values.startTime && values.endTime._d,
            image_path: imageAvatar,
            business_license_image: imageLicense,
            catering_service_license_image: imagePermit,
            ativities: ativitiesData
        }
        console.log(data);
        addRest(data).then(res => {
            console.log(res)
            message.success("添加成功")
            // mainForm.resetFields()
            window.location.reload()
        })
    };

    return (
        <div>
            <Form
                name="validate_other"
                form={mainForm}
                {...formItemLayout}
                initialValues={{
                    'ativities': '满减优惠',
                    'category': ['快餐便当', '简餐'],
                    'float_delivery_fee': 5,
                    'float_minimum_order_amount': 15
                }}
                onFinish={onFinish}
            >
                <Form.Item label="店铺名称" name='name'
                    rules={[{ required: true, message: '请输入店铺名称' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item label="详细地址" name='address'
                    rules={[{ required: true, message: '请输入详细地址' }]}
                >
                    <Input placeholder='请输入地址' />
                </Form.Item>
                <Form.Item label="联系电话" name='phone'
                    rules={[{ required: true, message: '请输入联系电话' }]}
                >
                    <Input addonBefore={prefixSelector} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="店铺简介" name='description'>
                    <Input />
                </Form.Item>
                <Form.Item label="店铺标语" name='promotion_info'>
                    <Input />
                </Form.Item>
                <Form.Item label="店铺分类" name='category' wrapperCol={{ span: 6 }}>
                    <Cascader options={getOption(category)} />
                </Form.Item>
                <Form.Item label="店铺特点" valuePropName="checked" wrapperCol={{ span: 10 }}>
                    <Checkbox.Group style={{ width: '100%' }} onChange={onChange}
                        defaultValue={Object.keys(character)}>
                        <Row>
                            <Col span={8}>
                                <Checkbox value="is_premium">品牌保证</Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="delivery_mode">蜂鸟专送</Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="new">新开店铺</Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="bao">外卖保</Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="zhun">准时达</Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="piao">开发票</Checkbox>
                            </Col>
                        </Row>
                    </Checkbox.Group>
                </Form.Item>
                <Form.Item label="配送费" name='float_delivery_fee'>
                    <InputNumber min={0} style={{ width: '150px' }} />
                </Form.Item>
                <Form.Item label="起送价" name='float_minimum_order_amount'>
                    <InputNumber min={0} style={{ width: '150px' }} />
                </Form.Item>
                <Form.Item label="营业起始时间" name='startTime'>
                    <TimePicker format={format} hourStep={1} minuteStep={15} />
                </Form.Item>
                <Form.Item label="营业结束时间" name='endTime'>
                    <TimePicker format={format} hourStep={1} minuteStep={15} />
                </Form.Item>
                {
                    [
                        { label: '上传店铺头像', img: imageAvatar },
                        { label: '上传营业执照', img: imageLicense },
                        { label: '上传餐饮服务许可证', img: imagePermit }
                    ].map(item => <Form.Item
                        label={item.label}
                        valuePropName="fileList"
                        key={item.label}
                    >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/v1/addimg/shop"
                            beforeUpload={beforeUpload}
                            onChange={(info) => handleChange(info, item.label)}
                            style={{ overflow: "hidden" }}
                        >
                            {
                                item.img
                                    ? <img src={'//elm.cangdu.org/img/' + item.img} alt="avatar" style={{ width: 120, height: 100, display: "block" }} />
                                    : <div>
                                        {loading[item.label] ? <LoadingOutlined /> : <PlusOutlined />}
                                    </div>
                            }
                        </Upload>
                    </Form.Item>)
                }
                <Form.Item label="优惠活动" name="ativities">
                    <Select onSelect={onSelect}>
                        <Option value="满减优惠">满减优惠</Option>
                        <Option value="优惠大酬宾">优惠大酬宾</Option>
                        <Option value="新用户立减">新用户立减</Option>
                        <Option value="进店领券">进店领券</Option>
                    </Select>
                </Form.Item>
                <Form.Item label="优惠活动">
                    <Table
                        columns={columns}
                        dataSource={ativitiesData}
                        pagination={{ position: [] }}
                        rowKey={(record) => record.description}
                    />
                </Form.Item>
                <Form.Item wrapperCol={{ span: 12, offset: 10 }}>
                    <Button type="primary" htmlType="submit">
                        立即创建
                    </Button>
                </Form.Item>
            </Form >
            <Modal title="提示"
                open={isModalOpen}
                onCancel={onCancel}
                footer={null}
            >
                <p>请输入活动详情</p>
                <Form form={actForm} onFinish={onModalFinish} >
                    <Form.Item name="description">
                        <Input />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 17 }}>
                        <Space>
                            <Button onClick={onCancel}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </div>

    );
};

export default App;